package com.frozenlab.android.weather.helper;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import android.util.Log;

public class HttpConnectHelper {

	private static final String TAG = "HttpConnectHelper";
	
	private HttpURLConnection connection;
	
	private void connectUrl(String strURL) throws IOException {	
		connection = (HttpURLConnection)new URL(strURL).openConnection();
		connection.connect();
		
		if(connection.getResponseCode() != HttpURLConnection.HTTP_OK){
			Log.e(TAG,"Something wrong with connection");
			connection.disconnect();
			throw new IOException("Error in connection: "+ connection.getResponseCode());
		}
		
	}
	
	public String getDataFromUrl(String strURL) throws IOException {

		Log.e(TAG,"getDataFromUrl");
		
		//verify url
		if (strURL == null){
			Log.e(TAG,"Invalid input URL");
			return null;
		}
		
		connectUrl(strURL);
		
		StringBuffer strBuf = new StringBuffer();
		
		try {
			InputStream inputStream = new BufferedInputStream(connection.getInputStream());

			BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream));
			String strLine = "";

			while ((strLine = buffReader.readLine()) != null) {
				strBuf.append(strLine + "\n");
			}

			buffReader.close();
			inputStream.close();
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		} finally {
			connection.disconnect();
		}

		return strBuf.toString();	
	}
	
	public Document getDocumentFromData(String strURL) throws IOException {
		
		Log.e(TAG,"getDocumentFromData");
		
		//verify url
		if (strURL == null){
			Log.e(TAG,"Invalid URL");
			return null;
		}

		//Get data from url
		String strDocContent = getDataFromUrl(strURL);
		
		if (strDocContent == null){
			Log.e(TAG,"Data is null");
			return null;
		}
		
		int strContentSize = strDocContent.length();
		StringBuffer strBuff = new StringBuffer();
		strBuff.setLength(strContentSize+1);
		strBuff.append(strDocContent);
		ByteArrayInputStream is = new ByteArrayInputStream(strDocContent.getBytes());

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		Document docData = null;
		
		try {
			db = dbf.newDocumentBuilder();
			docData = db.parse(is);
		} catch (Exception e) {
			Log.e(TAG,"Parser data error");
			return null;
		}
		
		return docData;
	}
	
	
		
	

}
